import {$http} from '@bana/miniapp-common-util'

Component({
  // 启用插槽
  options: {
    multipleSlots: true
  },
  data: {
    phoneNumber: '',
    imgCheckCode: '',
    checkCode: '',
    countdown: -1,
    hideStatus: true,
    sendStatus: true,
    codetext: '',
    oneTimeToken: '',
    tokenTimer: null,
    timeTimer: null,
    imgValidateSrc: '',
    uuid: '',
    outShowPhone: 0
  },
  /**
   * 组件的属性列表
   */
  properties: {
    outPhone: {
      type: Number,
      value: 0,
      observer(val) {
        const numVal = val + ''
        if (val && numVal.length === 11) {
          const showNumVal = numVal.substring(0, 3) + '****' + numVal.substring(7, 11)
          console.log('sms-checkcode outPhone====', val, showNumVal)
          this.setData({
            outShowPhone: showNumVal,
            phoneNumber: val
          })
        }
      }
    },
    btnText: {
      type: String,
      value: '提交'
    }
  },
  created() {

  },
  lifetimes: {
    attached() {
      this.init()
    },
    detached() {
      this.destroyed()
    }
  },
  methods: {
    init() {
      // 获取手机发送验证码token
      this.getOneTimeToken()
      // 获取图片uuid并得到图片验证码
      this.getUUid()
    },
    getOneTimeToken() {
      $http.post({
        url: 'shop/register/getOneTimeSmsUUID',
        success: ({data}) => {
          const resultData = data.resultData
          console.log('getOneTimeToken', resultData)
          this.setData({
            oneTimeToken: resultData
          })

          if (this.data.tokenTimer) {
            clearTimeout(this.data.tokenTimer)
          }
          const that = this
          const timer = setTimeout(function () {
            that.getOneTimeToken()
          }, 1000 * 60 * 14)
          this.setData({
            tokenTimer: timer
          })
        }
      })
    },
    /**
     * 填写手机号
     */
    setPhone(e) {
      const phoneNum = e.detail.value
      console.log('手机号', phoneNum)
      this.setData({
        phoneNumber: phoneNum
      })
    },
    /**
     * 填写图片验证码
     */
    setImgCheckCode(e) {
      const code = e.detail.value
      console.log('图片验证码', code)
      this.setData({
        imgCheckCode: code
      })
    },
    /**
     * 填写验证码
     */
    setCheckCode(e) {
      const code = e.detail.value
      console.log('验证码', code)
      this.setData({
        checkCode: code
      })
    },
    getSmsCode() {
      const isValidMobile = /^1[3-9]\d{9}$/.test(this.data.phoneNumber)
      if (!isValidMobile) {
        wx.showToast({
          title: '请填写正确的手机号',
          icon: 'none'
        })
        return
      }
      if (this.data.imgCheckCode) {
        $http.post({
          url: `shop/register/checkImgVerify/${this.data.imgCheckCode}/${this.data.uuid}`,
          success: ({data}) => {
            const resultData = data.resultData
            if (resultData) {
              this.sendSmsCode()
            } else {
              wx.showToast({
                title: '请填写正确的图片验证码',
                icon: 'none'
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: '请先填写图片验证码',
          icon: 'none'
        })
      }
    },
    sendSmsCode() {
      $http.post({
        url: 'shop/register/sendVerificationCodeNew/' + this.data.phoneNumber +
          `?_ud=${this.data.oneTimeToken}&_rd=${this.data.uuid}&_ic=${this.data.imgCheckCode}`,
        success: ({data}) => {
          const resultData = data.resultData
          console.log('验证码发送成功', resultData)
          // 禁用验证码view
          const that = this
          that.setData({
            sendStatus: false
          })
          wx.showToast({
            title: '验证码发送成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(function () {
            that.setData({
              hideStatus: false
            })
            that.data.countdown = 60
            that.timer()
          }, 2000)
          that.getOneTimeToken()
        },
        error: (error) => {
          console.log('验证码发送失败', error)
          this.getOneTimeToken()
        }
      })
    },
    timer() {
      console.log('timer')
      if (this.data.countdown > 0) {
        --this.data.countdown
        this.setData({
          codetext: '倒计时 ' + this.data.countdown + 's',
        })
        const that = this
        if (this.data.timeTimer) {
          clearTimeout(this.data.timeTimer)
        }
        const thisTimer = setTimeout(() => {
          that.timer()
        }, 1000)
        this.setData({
          timeTimer: thisTimer
        })
      } else {
        this.setData({
          hideStatus: true,
          sendStatus: true
        })
      }
    },
    getImgValidateSrc() {
      this.setData({
        imgValidateSrc: `${$http.baseUrl}/api/shop/register/getImgVerify/${this.data.uuid}?_r=${Math.random()}`
      })
    },
    getUUid() {
      const date = new Date()
      const monthStr = this.formatDate(date, 'yMd')

      this.setData({
        uuid: monthStr + this.randomString(10)
      })

      this.getImgValidateSrc()
    },
    randomString(len) {
      len = len || 32
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      const maxPos = chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : '0' + n
    },
    formatDate(date, format) {
      const formateArr = ['y', 'M', 'd', 'h', 'm', 's']
      const returnArr = []
      if (!date) {
        date = new Date()
      }
      returnArr.push(date.getFullYear())
      returnArr.push(this.formatNumber(date.getMonth() + 1))
      returnArr.push(this.formatNumber(date.getDate()))

      returnArr.push(this.formatNumber(date.getHours()))
      returnArr.push(this.formatNumber(date.getMinutes()))
      returnArr.push(this.formatNumber(date.getSeconds()))

      console.log('format date=======', formateArr, returnArr)
      for (let i = 0; i < returnArr.length; i++) {
        format = format.replace(formateArr[i], returnArr[i])
      }
      return format
    },
    destroyed() {
      if (this.data.tokenTimer) {
        clearTimeout(this.data.tokenTimer)
      }
    },
    submit() {
      console.log('提交了')
      const isValidMobile = /^1[3-9]\d{9}$/.test(this.data.phoneNumber)
      if (!isValidMobile) {
        wx.showToast({
          title: '请填写正确的手机号',
          icon: 'none'
        })
        return
      }
      if (this.data.imgCheckCode) {
        $http.post({
          url: `shop/register/checkImgVerify/${this.data.imgCheckCode}/${this.data.uuid}`,
          success: ({data}) => {
            const resultData = data.resultData
            if (resultData) {
              this.commit()
            } else {
              wx.showToast({
                title: '请填写正确的图片验证码',
                icon: 'none'
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: '请先填写图片验证码',
          icon: 'none'
        })
      }
    },
    commit() {
      if (!this.data.checkCode) {
        wx.showToast({
          title: '请先填写短信验证码',
          icon: 'none'
        })
      } else {
        $http.post({
          url: `shop/register/checkVerificationCode/${this.data.phoneNumber}/${this.data.checkCode}`,
          success: ({data}) => {
            const resultData = data.resultData
            if (resultData) {
              this.triggerEvent('submit', {
                phone: this.data.phoneNumber,
                checkCode: this.data.checkCode
              })
            } else {
              wx.showToast({
                title: '请填写正确的短信验证码',
                icon: 'none'
              })
            }
          }
        })
      }
    }
  }
})
